<template xmlns:v-quill='富文本编辑器'>
  <div class="container">
    <el-form label-position="top" label-width="80px" :model="article">
      <el-form-item label="文章标题">
        <el-input v-model="article.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章简介">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 6}"
          placeholder="请输入文章简介"
          v-model="article.desc">
        </el-input>
      </el-form-item>
      <el-form-item label="封面图">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:8000/api/article"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="imgPreview">
          <img v-if="article.cover_image" :src="article.cover_image" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div
          v-loading="imageLoading"
          element-loading-text="请稍等，图片上传中">
          <div class="quill-editor"
               :content="article.content"
               ref="customQuillEditor"
               @change="onEditorChange($event)"
               @blur="onEditorBlur($event)"
               @focus="onEditorFocus($event)"
               @ready="onEditorReady($event)"
               v-quill:myQuillEditor="editorOption">
          </div>
          <el-upload
            style="display: none"
            class="avatar-uploader"
            action="http://127.0.0.1:8000/api/article"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="imagesPreview">
            <img v-if="images" :src="images" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" id="article-uploader"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-button @click="send" type="success">{{sendText}}</el-button>
    </el-form>
  </div>
</template>
<script>
  import {sendArticle,postAlbum} from "../../api/article";

  const toolbar= [
    ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
    // ["blockquote", "code-block"], // 引用  代码块
    [{ header: 1 }, { header: 2 }], // 1、2 级标题
    // [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
    // [{ script: "sub" }, { script: "super" }], // 上标/下标
    // [{ indent: "-1" }, { indent: "+1" }], // 缩进
    // [{'direction': 'rtl'}],                         // 文本方向
    // [{ size: ["small", false, "large", "huge"] }], // 字体大小
    // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
    // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
    // [{ font: [] }], // 字体种类
    // [{ align: [] }], // 对齐方式
    // ["clean"], // 清除文本格式
    ["link", "image", "video"] // 链接、图片、视频
    ];

  export default {
    data () {
      return {
        article:{
          title:'',
          desc:'',
          cover_image:'',
          content:'',
        },
        sendText:'发布文章',    //上传文章的按钮文字
        imageLoading:false,    //图片上传等待
        images:'',    //文章中的图片文件
        imgFile:'',   //图片文件
        editorOption: {
          // some quill options
          modules: {
            toolbar: {
              container: toolbar,  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('#article-uploader').click();
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        }
      }
    },
    methods: {
      onEditorBlur(editor) {
        //失去焦点事件
        console.log('editor blur!', editor)
      },
      onEditorFocus(editor) {
        //获得焦点事件
        console.log('editor focus!', editor)
      },
      onEditorReady(editor) {
        // console.log('editor ready!', editor);
        // console.log(editor.getSelection);
      },
      onEditorChange({ editor, html, text }) {
        //内容改变事件
        // console.log('editor change!', editor, html, text);
        console.log(editor);
        this.article.content = html
      },
      imgPreview(file){
        const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是jpg,png,gif格式!');
        }
        else if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }else{
          this.article.cover_image=URL.createObjectURL(file.raw);
          this.imgFile=file.raw;
        }
      },
      imagesPreview(file){
        let vm=this;
        const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是jpg,png,gif格式!');
        }
        else if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }else{
          vm.imageLoading=true;
          const formData = new FormData();
          formData.append('images',file.raw);
          postAlbum(formData).then(res=>{
            console.log(res.data.images);
            let quill=vm.myQuillEditor;
            // 获取光标所在位置
            let length = quill.getLength();

            // 插入图片  res.info为服务器返回的图片地址
            quill.insertEmbed(length, 'image', res.data.images);

            // 调整光标到最后
            quill.setSelection(length + 1);
            // vm.article.content=vm.article.content+ "<img src=\"" + res.data.images + "\" style=\"max-width: 100%;cursor: zoom-in\" v-preview=\"" + res.data.images + '\"';
            vm.imageLoading=false;
            console.log(vm.article.content);
          }).catch(error=>{
            vm.$message.error('上传失败');
            vm.imageLoading=false;
          })
        }
      },
      send(){
        let vm=this;
        vm.sendText='发布中...';
        vm.article.content=(vm.article.content.replace(/<img/g,"<img style=\"max-width:100%\""));
        const formData = new FormData();
        formData.append('title',vm.article.title);
        formData.append('desc',vm.article.desc);
        formData.append('cover_image',vm.imgFile);
        formData.append('content',vm.article.content);
        sendArticle(formData).then(res=>{
          vm.$message.success('发布成功');
          // vm.$router.push('/');
          vm.sendText='发布文章';
        }).catch(error=>{
          vm.$message.error('发布失败');
          vm.sendText='发布文章';
        })
      },
    }
  }
</script>


<style lang="stylus" scoped>
  @import "../../stylus/color.styl";
  .container {
    width: 100%;
    max-width: 700px;
    margin: 0 auto;
    padding: 30px 0;
  }
  .quill-editor {
    min-height: 200px;
    overflow-y: auto;
  }




  /*上传封面图*/
  .avatar-uploader{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 300px;
    height: 200px;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  .avatar {
    width: 300px;
      height: 200px;
    display: block;
  }
</style>
